package com.autumn.platform.core.context.token.support;

import java.security.SecureRandom;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;

public class SecureRandomFactoryBean implements FactoryBean<SecureRandom> {

    private String algorithm = "SHA1PRNG";
    private Resource seed;

    @Override
    public SecureRandom getObject() throws Exception {
        SecureRandom rnd = SecureRandom.getInstance(algorithm);

        if (seed != null) {
            byte[] seedBytes = FileCopyUtils.copyToByteArray(seed.getInputStream());
            rnd.setSeed(seedBytes);
        } else {
            rnd.nextBytes(new byte[1]);
        }

        return rnd;
    }

    @Override
    public Class<SecureRandom> getObjectType() {
        return SecureRandom.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    public void setAlgorithm(String algorithm) {
        Assert.hasText(algorithm, "Algorithm required");
        this.algorithm = algorithm;
    }

    public void setSeed(Resource seed) {
        this.seed = seed;
    }
}
